package ui.fragment;

import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.ui.fragment.ServiceMessageFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import adapter.MineFragmentSetepAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.ItemBean;
import bean.PersonInfoBean;
import bean.UnreadMsgBean;
import event.MainPageEvent;
import student.andlei.com.student.R;
import ui.activity.MainActivity;
import ui.activity.MessageActivity;
import ui.fragment.minefragment.AboutUsFragment;
import ui.fragment.minefragment.BuyClassTimeFragment;
import ui.fragment.minefragment.FeedbackFragment;
import ui.fragment.minefragment.IntegralDetailFragment;
import ui.fragment.minefragment.IntegralRuleFragment;
import ui.fragment.minefragment.MyClassTimeFragment;
import ui.fragment.minefragment.MyPointsFragment;
import ui.fragment.minefragment.OrderMyFragment;
import ui.fragment.minefragment.PersonInfoFragment;
import ui.fragment.minefragment.SelectSchoolFragment;
import ui.fragment.minefragment.SettingFragment;
import ui.fragment.minefragment.StudyReportFragment;
import ui.fragment.minefragment.UpdatePasswordFragment;
import utils.GlideUtils;
import utils.GsonUtils;
import view.CircleImageView;

/**
 * 我的页面
 */
public class MineFragment extends BaseNetFragment {
    private RecyclerView lv;
    public CircleImageView imageView;
    public TextView tv_name,
            tv_school;
    private MineFragmentSetepAdapter adapter;
    private List<ItemBean> beanList = new ArrayList<>();
    private Fragment aboutusfragment,
            feedbackfragment,
            orderMyFragment,
            myclasstimefragment,
            mypointfragment,
            onlineserverfragment,
            settingfragment,
            studyreportfragment,
            personinfofragment,
            updatepasswordfragment,
            integraldetailfragment,
            integralrulefragment,
            buyclasstimefragment,
            selectschoolfragment;
    public String Updatetype = "";
    private ImageView img_msg;
    public static TextView tv_num;
//    @Override
//    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//        super.onViewCreated(view, savedInstanceState);
//        setTitle("我的");
//        hideBack();
//    }

//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//    }

    public static Fragment getInstance() {
        return new MineFragment();
    }


    @Override
    public void success(String action, BaseBean baseBean) {
        if (baseBean.code == 200) {
            if (action.equals("personal/getUnreadMsg")) {
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, UnreadMsgBean.class);
                if (bean.count <= 0) {
                    tv_num.setVisibility(View.GONE);
                } else {
                    tv_num.setText(bean.count + "");
                }
            }else if(action.equals("Qa/getNewsNumber")){
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,UnreadMsgBean.class);
                if(bean.count>0){
                    MainActivity.img_red_point.setText(bean.count+"");
                    MainActivity.img_red_point.setVisibility(View.VISIBLE);
                }else {
                    MainActivity.img_red_point.setVisibility(View.GONE);
                }
            } else {
                PersonInfoBean Bean = (PersonInfoBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), PersonInfoBean.class);
                GlideUtils.loadImageViewHeadphotoLoding(context, Bean.head_image, imageView);
                tv_name.setText("" + Bean.real_name);
                tv_school.setText(Bean.school_name + "\n" + Bean.schedule_name);
            }

        }
    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void findViews() {
        img_msg = getView(R.id.img_msg);
        tv_num = getView(R.id.tv_msg_number);
        imageView = getView(R.id.img_mine_photo);
        tv_name = getView(R.id.tv_mine_name);
        tv_school = getView(R.id.tv_mine_school_grade_class);
        lv = getView(R.id.list_mine_item);
    }

    @Override
    protected void formatViews() {
        EventBus.getDefault().register(this);
        img_msg.setOnClickListener(this);
        imageView.setOnClickListener(this);
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv.setLayoutManager(layoutManager);

        //创建适配器
        adapter = new MineFragmentSetepAdapter(context,R.layout.item_mine_setep, beanList);

        //给RecyclerView设置适配器
        lv.setAdapter(adapter);

        adapter.setOnItemClickListener(mOnItemClickListener);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    BaseQuickAdapter.OnItemClickListener mOnItemClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            hideAllFragment();
            switch (position) {
                //学习报告
                case 0:
                    updatestep(position);
                    if (studyreportfragment == null) {
                        studyreportfragment = StudyReportFragment.getInstance();
                    }
                    showFragment(studyreportfragment);
                    break;
                //我的订单
                case 1:
                    updatestep(position);
                    if (orderMyFragment == null) {
                        orderMyFragment = OrderMyFragment.getInstance();
                    }
                    showFragment(orderMyFragment);
                    break;
                //我的积分
                case 2:
                    updatestep(position);
                    if (mypointfragment == null) {
                        mypointfragment = MyPointsFragment.getInstance();
                    }
                    showFragment(mypointfragment);
                    break;
                //我的课时
                case 3:
                    updatestep(position);
                    if (myclasstimefragment == null) {
                        myclasstimefragment = MyClassTimeFragment.getInstance();
                    }
                    showFragment(myclasstimefragment);
                    break;
                //在线客服
                case 4:
                    updatestep(position);
                    if (onlineserverfragment == null) {
                        // 访客来源信息
                        ConsultSource source = new ConsultSource("", "标题", "custom information string");
                        /**
                         * 构造一个 ViewGroup，用于放置sdk的评价和人工客服按钮。
                         * 该控件推荐放在标题栏右边。可以用以下两种方式：
                         * 1. 将 container 放到 layout 文件中
                         * LinearLayout sdkIconContainer = (LinearLayout)findViewById(R.id.xxx);
                         * 2. 动态构建，动态添加
                         * LinearLayout sdkIconContainer = new LinearLayout(this);
                         * sdkIconContainer.setOrientation(LinearLayout.HORIZONTAL);
                         * 构造好后，还需要将 ViewGroup 添加到你的 Activity 中
                         */
                        LinearLayout sdkIconContainer = new LinearLayout(context);
                        sdkIconContainer.setOrientation(LinearLayout.HORIZONTAL);
                        ServiceMessageFragment fragment = Unicorn.newServiceFragment("", source, sdkIconContainer);
                        onlineserverfragment = fragment;
                        //OnlineServerFragment.getInstance();
                    }
                    showFragment(onlineserverfragment);
                    break;
                //意见反馈
                case 5:
                    updatestep(position);
                    if (feedbackfragment == null) {
                        feedbackfragment = FeedbackFragment.getInstance();
                    }
                    showFragment(feedbackfragment);
                    break;
                //关于我们
                case 6:
                    updatestep(position);
                    if (aboutusfragment == null) {
                        aboutusfragment = AboutUsFragment.getInstance();
                    }
                    showFragment(aboutusfragment);
                    break;
                //设置
                case 7:
                    updatestep(position);
                    if (settingfragment == null) {
                        settingfragment = SettingFragment.getInstance();
                    }
                    showFragment(settingfragment);
                    break;
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainPageEvent event) {
        if (event.firstPage == MainPageEvent.MINE_PAGE) {
            mOnItemClickListener.onItemClick(adapter, null, event.secondPage);
        }
    }

    private void updatestep(int position){
        for(ItemBean bean : beanList){
            bean.isSelect = 0;
        }
        beanList.get(position).isSelect = 1;
        adapter.notifyDataSetChanged();
    }
    //
    private void loadData() {
        post("personal/getInfo", BaseBean.class, false);
    }
    @Override
    protected void formatData() {
        loadData();
        aboutusfragment = AboutUsFragment.getInstance();
        feedbackfragment = FeedbackFragment.getInstance();
        orderMyFragment = OrderMyFragment.getInstance();
        myclasstimefragment = MyClassTimeFragment.getInstance();
        mypointfragment = MyPointsFragment.getInstance();
        // 访客来源信息
        ConsultSource source = new ConsultSource("", "", "custom information string");
        /**
         * 构造一个 ViewGroup，用于放置sdk的评价和人工客服按钮。
         * 该控件推荐放在标题栏右边。可以用以下两种方式：
         * 1. 将 container 放到 layout 文件中
         * LinearLayout sdkIconContainer = (LinearLayout)findViewById(R.id.xxx);
         * 2. 动态构建，动态添加
         * LinearLayout sdkIconContainer = new LinearLayout(this);
         * sdkIconContainer.setOrientation(LinearLayout.HORIZONTAL);
         * 构造好后，还需要将 ViewGroup 添加到你的 Activity 中
         */
        LinearLayout sdkIconContainer = new LinearLayout(context);
        sdkIconContainer.setOrientation(LinearLayout.HORIZONTAL);
        ServiceMessageFragment fragment = Unicorn.newServiceFragment("", source, sdkIconContainer);
        onlineserverfragment =fragment;
                //OnlineServerFragment.getInstance();
        settingfragment = SettingFragment.getInstance();
        studyreportfragment = StudyReportFragment.getInstance();
        personinfofragment = PersonInfoFragment.getInstance();
        integraldetailfragment = IntegralDetailFragment.getInstance();
        integralrulefragment = IntegralRuleFragment.getInstance();
        buyclasstimefragment = BuyClassTimeFragment.getInstance();
        updatepasswordfragment = UpdatePasswordFragment.getInstance();
        selectschoolfragment = SelectSchoolFragment.getInstance();
        addFragment(R.id.details_layout, personinfofragment);
        addFragment(R.id.details_layout, aboutusfragment);
        addFragment(R.id.details_layout, orderMyFragment);
        addFragment(R.id.details_layout, feedbackfragment);
        addFragment(R.id.details_layout, myclasstimefragment);
        addFragment(R.id.details_layout, mypointfragment);
        addFragment(R.id.details_layout, onlineserverfragment);
        addFragment(R.id.details_layout, settingfragment);
        addFragment(R.id.details_layout, studyreportfragment);
        addFragment(R.id.details_layout, integraldetailfragment);
        addFragment(R.id.details_layout, integralrulefragment);
        addFragment(R.id.details_layout, buyclasstimefragment);
        addFragment(R.id.details_layout, updatepasswordfragment);
        addFragment(R.id.details_layout, selectschoolfragment);
        hideAllFragment();
        showFragment(personinfofragment);
        String[] seteps = {"学习报告", "我的订单", "我的积分", "我的课时", "在线客服", "意见反馈", "关于我们", "设置"};
        for (int i = 0; i < seteps.length; i++) {
            ItemBean bean = new ItemBean();
            bean.setStr(seteps[i]);
            beanList.add(bean);
        }

    }

    //隐藏所有Fragment
    public void hideAllFragment() {
        hideFragment(aboutusfragment);
        hideFragment(feedbackfragment);
        hideFragment(orderMyFragment);
        hideFragment(myclasstimefragment);
        hideFragment(mypointfragment);
        hideFragment(onlineserverfragment);
        hideFragment(settingfragment);
        hideFragment(studyreportfragment);
        hideFragment(personinfofragment);
        hideFragment(integraldetailfragment);
        hideFragment(integralrulefragment);
        hideFragment(buyclasstimefragment);
        hideFragment(updatepasswordfragment);
        hideFragment(selectschoolfragment);
    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_mine_photo:
                hideAllFragment();
                if (personinfofragment == null) {
                    personinfofragment = PersonInfoFragment.getInstance();
                } else {
                    showFragment(personinfofragment);
                }
                break;
            case R.id.img_msg:
                jumpTo(MessageActivity.class);
                break;
        }
    }

    //显示更改密码
    public void GojumpUpdateFragment() {
        hideAllFragment();
        if (updatepasswordfragment == null) {
            updatepasswordfragment = UpdatePasswordFragment.getInstance();
        } else {
            showFragment(updatepasswordfragment);
        }
    }

    //显示更改密码
    public void GojumpSettingFragment() {
        hideAllFragment();
        if (settingfragment == null) {
            settingfragment = SettingFragment.getInstance();
        }
        showFragment(settingfragment);
    }

    //显示所属学校
    public void GojumpSelectSchoolFragment() {
        hideAllFragment();
        if (selectschoolfragment == null) {
            selectschoolfragment = SelectSchoolFragment.getInstance();
        }
        showFragment(selectschoolfragment);
    }

    //显示个人信息
    public void GojumpPersoninfoFragment() {
        hideAllFragment();
        if (personinfofragment == null) {
            personinfofragment = PersonInfoFragment.getInstance();
        }
        showFragment(personinfofragment);
    }

    //显示我的积分
    public void GojumpMyPointFragment() {
        hideAllFragment();
        if (mypointfragment == null) {
            mypointfragment = PersonInfoFragment.getInstance();
        }
        showFragment(mypointfragment);
    }

    //显示积分明细
    public void GojumpIntegraldetailfragment() {
        hideAllFragment();
        if (integraldetailfragment == null) {
            integraldetailfragment = IntegralDetailFragment.getInstance();
        }
        showFragment(integraldetailfragment);
    }

    //显示积分规则
    public void GojumpIntegralRuleFragment() {
        hideAllFragment();
        if (integralrulefragment == null) {
            integralrulefragment = IntegralRuleFragment.getInstance();
        } else {
            showFragment(integralrulefragment);
        }
    }

    //显示我的积分
    public void GojumpMyPointsFragment() {
        hideAllFragment();
        if (mypointfragment == null) {
            mypointfragment = MyPointsFragment.getInstance();
        }
        showFragment(mypointfragment);
    }

    //显示我的课时
    public void GojumpMyClassTimeFragment() {
        hideAllFragment();
        if (myclasstimefragment == null) {
            myclasstimefragment = MyClassTimeFragment.getInstance();
        } else {
            showFragment(myclasstimefragment);
        }
    }

    //显示购买课时
    public void GojumpBuyClassTimeFragment() {
        hideAllFragment();
        if (buyclasstimefragment == null) {
            buyclasstimefragment = BuyClassTimeFragment.getInstance();
        } else {
            showFragment(buyclasstimefragment);
        }
    }

    /**
     * 这段可以解决fragment嵌套fragment会崩溃的问题
     */
    @Override
    public void onDetach() {
        super.onDetach();
        try {
            //参数是固定写法
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            loadData();
            post("Qa/getNewsNumber",BaseBean.class,false);
            post("personal/getUnreadMsg",BaseBean.class,false);
        }
    }
}
